package cmsc427.mw5.app;


import cmsc427.mw5.*;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

public class ContactAdapter extends ArrayAdapter<Contact> {

	private int selectedPosition;
	
	public ContactAdapter(Context context, int resource, int textViewResourceId) {
		super(context, resource, textViewResourceId);
		selectedPosition = 0;
	}
	
	@Override
	public View getView(int position, View covertView, ViewGroup parent){
		
		// get the default view (adds getItem(position).toString() to View 
		// corresponding to txtViewResourceId
		View row = super.getView(position, covertView, parent);
		
		// add the image to the row before it gets returned 
		try {
			ImageView imgView = (ImageView) row.findViewById(R.id.imgContactImage);
			imgView.setImageResource(getItem(position).getImage());
		} catch(ClassCastException e){
			// didn't get an image view back, unexpected
		} catch(NullPointerException e){
			// didn't get any view back, unexpected
		}
		
		// display additional objects here...
		
		// handle if the view is selected
		if(getContact(position).isSelected()){
			row.setBackgroundResource(android.R.color.background_light);
		} else {
			row.setBackgroundResource(android.R.color.background_dark);
		}
		
		// return the complete row
		return row;
	}

	public void setSelectedContact(int position){
		if(position >= 0 && position < getCount()){
			getSelectedContact().setSelected(false);
						
			this.selectedPosition = position;
			getSelectedContact().setSelected(true);
			
			notifyDataSetChanged();
		}
		
	}
	
	public int getSelectedPosition(){
		return this.selectedPosition;
	}
	
	public Contact getSelectedContact(){
		return getContact(getSelectedPosition());
	}
	
	public Contact getContact(int position){
		return getItem(position);
	}
}
